package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.UserService;
import entityJPA.User;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private int index = 0;
	private static final long serialVersionUID = 1L;

	@EJB
	private UserService userService;

	private PrintWriter out;

	private int displace = 4;
	/**
	 * @see HttpServlet#HttpServlet()
	 */

	public UserServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession h = request.getSession();
		h.setAttribute("indexUserList", index);
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession h = request.getSession();
		out = response.getWriter();
		List<User> userList = null;
		boolean ok=false;
		try {
			if (request.getParameter("addUser") != null) {
				add(request);
				ok=true;
			} else if (request.getParameter("updateUser") != null) {
				update(request);
				ok=true;
			} else if (request.getParameter("deleteUser") != null) {
				delete(request);
				ok=true;
			}
		} catch (Exception e) {
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("ExceptionHandler.jsp");
		}
		try {
			if (request.getParameter("searchUserButton") != null) {
				if (request.getParameter("searchUser").equals("firstName")) {
					userList = userService.filterByFirstName(request
							.getParameter("NameSearch"));
				} else {
					userList = userService.filterByLastName(request
							.getParameter("NameSearch"));
				}
			} else {
				if (request.getParameter("next") != null) {
					if (index + displace >= userService.getTotal()) {
						index = 0;
					} else {
						index += displace;
					}
				} else if (request.getParameter("previous") != null) {
					if (index - displace < 0) {
						index = 0;
					} else {
						index -= displace;
					}

				}

				userList = userService.getActiveUsers(index, displace);
			}
			h.setAttribute("userList", userList);
			if(ok==true){
				h.setAttribute("operationIsSuccesful", "yes");
			}
			else{
				h.setAttribute("operationIsSuccesful", "no");
			}
		} catch (Exception e) {
			h.setAttribute("exceptionMessage",
					"An error occured while trying to process your request. Please try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
		h.setAttribute("indexUserList", index);
		response.sendRedirect("user.jsp");

	}

	private List<User> getUsers() throws Exception {
		return userService.getUserFindAll();
	}

	private void add(HttpServletRequest request) throws Exception {

		User u = new User();
		u.setFirstName(request.getParameter("firstName"));
		u.setLastName(request.getParameter("lastName"));
		u.setHomeNumber(request.getParameter("homeNumber"));
		u.setCellNumber(request.getParameter("cellNumber"));
		u.setEmail(request.getParameter("email"));
		u.setRank(request.getParameter("rank"));
		u.setDescription(request.getParameter("description"));
		u.setUsertype(userService.getUsertypeByTitle(request
				.getParameter("userType")));
		// out = response.getWriter();

		userService.addUser(u);

	}

	private void update(HttpServletRequest request) throws Exception {

		User user = userService.getUserById(Integer.parseInt(request
				.getParameter("id")));
		user.setFirstName(request.getParameter("firstName"));
		user.setLastName(request.getParameter("lastName"));
		// user.setPassword(request.getParameter("password"));
		user.setHomeNumber(request.getParameter("homeNumber"));
		user.setCellNumber(request.getParameter("cellNumber"));
		user.setEmail(request.getParameter("email"));
		user.setRank(request.getParameter("rank"));
		user.setDescription(request.getParameter("description"));
		user.setUsertype(userService.getUsertypeByTitle(request
				.getParameter("userType")));

		userService.editUser(user);

	}

	private void delete(HttpServletRequest request) throws Exception {
		User user = userService.getUserById(Integer.parseInt(request
				.getParameter("id")));

		userService.deleteUser(user);

	}

}
